import React from 'react';
import Container from '@icedesign/container';
import styles from './index.module.scss';
import event from '@/request'
import {Button, Dialog, Input, MenuButton, Message, Table} from "@alifd/next";
import ZgDialog from '@/components/ZgDialog';
import {Link} from "react-router-dom";
import $http from '@/service/Services';

const {Item} = MenuButton;


/**
 * list
 */
class UserListComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            orgId: "",
            userType: props.user, //user admin
            current: 0,
            mockData: [],
            selectedList: [],
            condition: "",
            tenant:{},
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        // 当前页数
        this.pageNum = 1;
        // 分页每页显示数据条数
        this.pageSize = 10;
        // 数据总条数
        this.totalNum = 0;
        this.$http = $http;
        this.cancelCall = this.cancelCall.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.onPageChange = this.onPageChange.bind(this);
        this.getUserManageList = this.getUserManageList.bind(this);
        this.deleteTenantUser = this.deleteTenantUser.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const id = this.props.orgId;
        this.setState({
            orgId: id
        }, () => {
            this.getUserManageList();
            this.geOrg();
        });
    };

    /**
     * 获取tenant的信息
     */
    geOrg = () => {
        const that = this;
        this.$http.get( event.event.url + '/v1/org/getOrgEditById/' + this.state.orgId)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    that.setState({
                        tenant: data.data
                    })
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };
    /**
     * 条件
     * @param e
     * @param value
     */
    searchCondition = (value, e) => {
        this.setState({
            condition: value,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        });
        this.pageNum = 1;
    };
    /**
     * 改变页面
     * @param currentPage
     */
    onPageChange = (currentPage) => {
        this.state = {
            current: currentPage,
            mockData: this.props.mockData,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        this.getUserManageList();
    };
    /**
     * 修改分页数据
     * @param currentPage
     */
    onChangePage = (currentPage) => {
        this.setState({
            loading: true,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        });
        setTimeout(() => {
            this.getUserManageList(currentPage);
            this.setState({
                loading: false,
                config: {
                    data: null,
                    visible: false,
                    title: "",
                    content: ""
                }
            });
        }, 0);
    };

    /**
     * 获取数据
     */
    getUserManageList = () => {
        const _this = this;
        let url = event.event.url + '/v1/user/getUserPage ';
        this.$http.post(url,
            {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                condition: {
                    name: this.state.condition
                }
            })
            .then(function (response) {
                const {data} = response;
                const mockData = data.data.voList;
                _this.totalNum = data.data.total;
                mockData.forEach((o, i) => {
                    o.number = i + 1;
                });

                _this.setState({
                    mockData: mockData,
                    config: {
                        data: null,
                        visible: false,
                        title: "",
                        content: ""
                    }
                });
            })
            .catch(function (error) {
                console.log(error);
                Message.error(error.message);
            })

    };


    /**
     * 删除
     */
    deleteTenantUser = (row) => {
        this.setState({
                config: {
                    data: row,
                    visible: true,
                    title: "提示消息",
                    content: "删除后不能恢复，确认要删除？"
                }
            }
        )
    };

    /**
     * 取消按钮的操作
     */
    cancelCall = () => {
        this.setState({
            config: {
                visible: false
            }
        });
        console.log("点击取消按钮 .");
    };


    /**
     * 删除
     */
    okCall = (data) => {
        this.setState({
            config: {
                visible: false
            }
        });
        const _this = this;
        this.$http.post(event.event.url + '/v1/user/deleteUser', {userId: data.id, orgId: this.state.orgId})
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success("操作成功.");
                    _this.getUserManageList();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };


    /**
     *  批量操作
     * @param text
     */
    handleClick = () => {
        const {selectedList} = this.state;
        if (selectedList.length == 0) {
            Message.error("请选择需要删除的数据.");
            return null;
        }
        this.setState({
            visible: true
        });
    };

    /**
     *
     * @param args
     */
    onChange = (...args) => {
        this.setState({
            selectedList: args
        });
    };


    /**
     * 取消提示弹框
     */
    onCloseDialog = reason => {
        this.setState({
            visible: false
        });
    };


    render() {
        const {mockData} = this.state;
        const user = JSON.parse(sessionStorage.getItem("userInfoVO"));
        return (
            <Container className='container-main'>
                <div className='container-btnBox' style={{marginTop: '0'}}>
                    <div className={styles.buttons}>
                        <Link
                            to={"userEdit?id=&orgId=" + this.state.orgId}><Button
                            className='pipe-btn-add'>新建用户</Button></Link>

                        <span className={styles.caseNumber}>
                                <Input onChange={this.searchCondition.bind(this)} placeholder={"请输入登录名/用户名称"}
                                       className={`${styles.input} ${styles.shortInput}`}/>
                                <Button
                                    type="primary"
                                    className='pipe-btn-search'
                                    onClick={this.getUserManageList}
                                >
                                查询
                                </Button>
                            </span>
                    </div>
                </div>
                <div className='container-btnBox' style={{margin: '10px 0'}}>
                    <div className={styles.buttons} style={{float: 'right',height: '40px',lineHeight: '40px'}}>
                        当前租户：{this.state.tenant.name}
                    </div>
                </div>
                <div className='container-table'>
                    <Table dataSource={mockData} primaryKey="id" className={styles.table}>
                        <Table.Column align="center" title="登录名" dataIndex="account"/>
                        <Table.Column align="center" title="用户名称" dataIndex="name"/>
                        <Table.Column align="center" title="绑定手机" dataIndex="phone"/>
                        <Table.Column align="center" title="绑定邮箱" dataIndex="email"/>
                        <Table.Column align="center" title="操作" cell={
                            (value, index, record) => {
                                console.log(user);
                                if (user.id !== record.id  ||  user.type == 2 ) {
                                    return (
                                        <div>
                                            <Button type="normal" size="small" text className='pipe-btn-edit'>
                                                <Link
                                                    to={"userEdit?id=" + record.id + "&orgId=" + this.state.orgId}>修改</Link>
                                            </Button>
                                            <Button type="normal" size="small" text className='pipe-btn-delete'
                                                    onClick={this.deleteTenantUser.bind(this, record)} warning>
                                                <a onClick={() => {
                                                }}>删除</a>
                                            </Button>
                                        </div>
                                    )
                                } else {
                                    return null;
                                }

                            }
                        }/>
                    </Table>
                    <ZgDialog config={this.state.config} cancelCall={this.cancelCall} okCall={this.okCall}/>
                    <Dialog
                        className='pipe-dialog'
                        title="提示信息"
                        visible={this.state.visible}
                        onOk={this.onOkDialog}
                        onCancel={this.onCloseDialog.bind(this, 'cancelClick')}
                        onClose={this.onCloseDialog}>
                        删除后不能恢复，确认要删除？
                    </Dialog>
                </div>
                {/**
                 * 分页
                 * defaultCurrent 初始页码
                 * total 总记录数
                 * pageSize 一页中的记录数
                 */}

            </Container>
        )
            ;
    }

}

export default UserListComponent;
